package com.atguigu.gulimail.auth.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimail.auth.feign.MemberFeign;
import com.atguigu.gulimail.auth.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    MemberFeign memberFeign;

    @GetMapping({"/login.html",})
    public String indexPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute!=null){
            return "redirect:http://gulimail.com";
        }else {
            return "login";

        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo , HttpSession session, RedirectAttributes redirectAttributes){
        //TODO 调用登录服务
        R r=memberFeign.login(userLoginVo);
        if(r.getCode()==0){
            String data = JSON.toJSONString(r.get("data"));
            MemberResponseVo res = JSON.parseObject(data, MemberResponseVo.class);
            if(res!=null){
                session.setAttribute(AuthServerConstant.LOGIN_USER,res);
            }else {
                return "redirect:http://auth.gulimail.com/login.html";
            }
            return "redirect:http://gulimail.com";
        }else {
            Map<String,String> errors=new HashMap<>();
            errors.put("msg",r.getMsg());
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimail.com/login.html";
        }
    }
}
